package com.serverapk.camera;

import java.util.Arrays;



import com.serverapk.util.ToolsUtil;

import android.util.Log;

public class MediaStream {

	private static final String TAG = "MediaStream";
	public static final int MEDIA_RES_BUF_LEN = 20;
	public static final int MEDIA_HDR_BUF_LEN = 20;

	public static final int MEDIA_HDR_FORMAT = 0x03;

	public static final int MEDIA_RES_FORMAT = 0x10;
	public static final int MEDIA_RES_SUCESS = 200;  //成功
	public static final int MEDIA_RES_NO_PERMISSION = 203;  //无权限
	public static final int MEDIA_RES_FORBIDDEN = 403; //被禁用

	public int parseMediaRes(byte[] media_res) {
		int i = 0;
		int len = 0;
		int ret = 0;
		int media_format = 0;
		// '$' ascii 0x24
//		Log.d(TAG, ToolsUtil.getCurrentTime() + " >>>:" + Arrays.toString(media_res));
		if (media_res[i++] == 0x24 && media_res[i++] == 0x24) {
			len = media_res[i++];
			if (len == MEDIA_RES_BUF_LEN) {
				media_format = media_res[i++];
				if (media_format == MEDIA_RES_FORMAT) {
					byte[] res_code = new byte[2];
					res_code[0] = media_res[i++];
					res_code[1] = media_res[i++];
					ret = ToolsUtil.bytes2Short(res_code);
				}
			}
		}
		return ret;
	}

	public int parseMediaHdr(byte[] media_hdr) {

		int i = 0;
		int len = 0;
		int ret = 0;
		int media_format = 0;
		int width = 0;
		int height = 0;
		byte frame_rate = 0;
		int frame_type = 0;

		// '$' ascii 0x24
//		Log.d(TAG, ToolsUtil.getCurrentTime() + " >>>:" + Arrays.toString(media_hdr));
		Log.d(TAG, ">>>>>>>>>:" + System.currentTimeMillis());
		if (media_hdr[i++] == 0x24 && media_hdr[i++] == 0x24) {
			len = media_hdr[i++];
			if (len == MEDIA_HDR_BUF_LEN) {
				media_format = media_hdr[i++];
				if (media_format == MEDIA_HDR_FORMAT) {
					frame_type = media_hdr[i++]; // frame_type 0xF0

					frame_rate = media_hdr[i++]; // frame_rate
//					Log.d(TAG, "=====> frame_rate:" + ToolsUtil.getUnsignedByte(frame_rate));
					width = ToolsUtil.getUnsignedByte(media_hdr[i++]); // width
//					Log.d(TAG, "=====> width:" + width * 8);
					height = ToolsUtil.getUnsignedByte(media_hdr[i++]); // height
//					Log.d(TAG, "=====> height:" + height * 8);

					byte[] tmp = new byte[4];
					tmp[0] = media_hdr[i++];
					tmp[1] = media_hdr[i++];
					tmp[2] = 0;
					tmp[3] = 0;
					len = ToolsUtil.bytes2Int(tmp);
					Log.d(TAG, "=====> timestamp:" + len);

					i++; // resv[0]
					i++; // resv[1]

					tmp[0] = media_hdr[i++];
					tmp[1] = media_hdr[i++];
					tmp[2] = media_hdr[i++];
					tmp[3] = media_hdr[i++];
					len = ToolsUtil.bytes2Int(tmp);
					Log.d(TAG, "=====> datetime:" + len);

					tmp[0] = media_hdr[i++];
					tmp[1] = media_hdr[i++];
					tmp[2] = media_hdr[i++];
					tmp[3] = media_hdr[i++];
					ret = ToolsUtil.bytes2Int(tmp);
//					Log.d(TAG, "=====> size:" + ret);
				}
			}
		}
		return ret;
	}

	public void writeToFile() {

	}

}
